package com.pn.service.impl;

import com.pn.entity.InStore;
import com.pn.entity.Result;
import com.pn.mapper.ProductMapper;
import com.pn.mapper.PurchaseMapper;
import com.pn.page.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.pn.mapper.InStoreMapper;
import com.pn.service.InStoreService;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.util.List;

@Service
public class InStoreServiceImpl implements InStoreService {

    @Resource
    private InStoreMapper inStoreMapper;
    @Resource
    private PurchaseMapper purchaseMapper;
    @Resource
    private ProductMapper productMapper;

    @Transactional
    @Override
    public Result saveInStore(InStore inStore, Integer buyId) {

        int i = inStoreMapper.insertInStore(inStore);

        if (i > 0) {
            // 修改采购单状态为已入库
            int j = purchaseMapper.updatePurchaseIsInById(buyId);
            if (j > 0) {
                return Result.ok("入库单添加成功！");
            }

            Result.err(Result.CODE_ERR_BUSINESS, "入库单添加失败！");
        }

        return Result.err(Result.CODE_ERR_BUSINESS, "入库单添加失败！");
    }

    @Override
    public Page queryInstorePage(Page page, InStore inStore) {

        List<InStore> instoreRows = inStoreMapper.selectInstorePage(page, inStore);
        int rows = inStoreMapper.countInstore(inStore);

        page.setResultList(instoreRows);
        page.setTotalNum(rows);

        return page;
    }

    @Transactional
    @Override
    public Result setIsInById(InStore inStore) {

        // 1)修改入库单状态为已入库（1）
        int i = inStoreMapper.updateIsInById(inStore.getInsId());
        if (i > 0) {
            //  2)增加商品表的库存数量
            int j = productMapper.updateInventById(inStore.getProductId(), inStore.getInNum());
            if (j > 0) {
                return Result.ok("确认入库成功！");
            }
            return Result.err(Result.CODE_ERR_BUSINESS, "确认入库失败！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "确认入库失败！");
    }
}
